package com.example.mynewsapp.activity

import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.example.mynewsapp.R
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.model.NewsItem
import com.example.mynewsapp.util.DatabaseHelper
import kotlinx.android.synthetic.main.detail_news.*

class DetailNews : AppCompatActivity() {

    companion object {
        const val DETAIL_NEWS = "DETAIL_NEWS"
    }

    var newsItem: NewsItem? = null
    var newsUrl: String? = null
    var newsTitle: String? = null
    var subTitle: String? = null

    var isFavorite: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.detail_news)

        //依靠DatabaseHelper的构造函数创建数据库
        val dbHelper = DatabaseHelper(this, "news_db", null, 1)
        db = dbHelper.writableDatabase

        setSupportActionBar(toolbar)
        assert(supportActionBar != null)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)

        progressBar.max = 100


        // 获取数据
        newsItem = intent.getParcelableExtra(DETAIL_NEWS)


        if (newsItem != null){

            newsUrl = newsItem?.url
            newsTitle = newsItem?.title
            subTitle = newsItem?.country

            if (newsItem?.like == "yes"){
                favorite_btn.setBackgroundResource(R.drawable.set_favorite)
                isFavorite = true
            }

            tvTitle.text = newsTitle
            tvSubTitle.text = subTitle


            // 分享
            imageShare.setOnClickListener {
                val share = Intent(Intent.ACTION_SEND)
                share.type = "text/plain"
                share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
                share.putExtra(Intent.EXTRA_TEXT, newsUrl)
                startActivity(Intent.createChooser(share, getString(R.string.share)))
            }
            // 收藏按钮
            favorite_btn.setOnClickListener {
                isFavorite = !isFavorite
                if (isFavorite) {
                    favorite_btn.setBackgroundResource(R.drawable.set_favorite)
                } else {
                    favorite_btn.setBackgroundResource(R.drawable.ic_favorite)
                }
            }

            // 显示
            showWebView()
        }
    }
    // webview 显示
    private fun showWebView() {
        webView.settings.loadsImagesAutomatically = true
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.settings.setSupportZoom(true)
        webView.settings.builtInZoomControls = true
        webView.settings.displayZoomControls = false
        webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
        webView.loadUrl(newsUrl!!)

        progressBar.progress = 0

        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                tvTitle.text = getString(R.string.newsDetail)
                progressBar.progress = 0
                try{
                    if(!url.startsWith("http://") && !url.startsWith("https://")){
                        var intent = Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                }catch (e: Exception){//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                newsUrl = url
                invalidateOptionsMenu()
            }

            override fun onPageFinished(view: WebView, url: String) {
                progressBar.visibility = View.GONE
                invalidateOptionsMenu()
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onStop() {
        super.onStop()

        if (newsItem?.url == "") return

        var isExist = false
        val cursor = db!!.query("favorite", null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val url = cursor.getString(cursor.getColumnIndex("newsUrl"))
            if (url == newsItem?.url) {
                isExist = true
                if (!isFavorite) {
                    db!!.delete("favorite","newsUrl=?", arrayOf(url))
                }
                break
            }
        }
        cursor.close()
        if (!isExist && isFavorite) {
            //创建存放数据的ContentValues对象
            val values = ContentValues()
            values.put("newsImage", newsItem!!.image)
            values.put("newsUpdate", newsItem!!.update)
            values.put("newsCountry", newsItem!!.country)
            values.put("newsTitle", newsItem!!.title)
            values.put("newsDate", newsItem!!.date)
            values.put("newsUrl", newsItem!!.url)
            values.put("newsLike", "yes")
            //数据库执行插入命令
            db!!.insert("favorite", null, values)
        }
    }
}